package 网络编程.homework;

import 网络编程.utils.StreamUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName Homework03Server.java
 * @Description 文件下载服务端
 * @createTime 2023年05月04日 15:06:00
 */
public class Homework03Server {
    public static void main(String[] args) throws Exception {
        //1.监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //2.等待客服端连接
        System.out.println("服务端，在9999端口监听，等待下载文件");
        Socket socket = serverSocket.accept();
        //3.读取 客服端发送要下载的文件名
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        String downLoadFileName = "";
        while ((len = inputStream.read(b))!=-1){
            downLoadFileName += new String(b,0,len);
        }
        System.out.println("客服端希望下载文件名" + downLoadFileName);

        //服务器上有两个文件，1.png love.jpg 如果客户下载的是 1.png我们就返回该文件，否则一律返回 love.jpg
        String resFileName = "";
        if ("1".equals(downLoadFileName)){
            resFileName = "D:\\files\\1.png";
        }else {
            resFileName = "D:\\files\\love.jpg";
        }
        //4.创建一个输入流，读取文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(resFileName));

        //5.使用工具类StreamUtils,读取文件到一个字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //6.得到Socket关联的输出流
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        //7.写入到数据通道，返回给客服端
        bos.write(bytes);
        //结束标志
        socket.shutdownOutput();

        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出");
    }
}
